import { Form, Button, Row, Col } from "antd";
import type { FormProps } from "antd";
import { useState, useMemo, useEffect } from "react";
import { DownOutlined } from "@ant-design/icons";
import type { SearchFormItem } from "../Index";
import { SearchInput, SearchSelect, SearchDatePicker } from "./seach-element";
import dayjs from "dayjs";
// const { RangePicker } = DatePicker;
// 搜索表单组件
const TableSearch = ({
	searchForm,
	formItemLayout,
	searchFinish,
}: {
	searchForm?: SearchFormItem[];
	formItemLayout?: any;
	searchFinish?: (values?: any) => void;
	getDefualtSearchParams?: (values?: any) => void;
}) => {
	// 表单实例
	const [form] = Form.useForm();
	// 展开状态
	const [expand, setExpand] = useState(false);
	// 默认列宽
	const defaultSpan = 6;
	// 主色调
	const primaryColor = "var(--primary)";
	// 搜索表单提交
	const onFinish: FormProps<any>["onFinish"] = (values) => {
		console.log("submit1", values);
		// 将values转换为数组
		const valuesArray = Object.entries(values).map(([key, value]) => ({ key, value }));

		// 如果存在范围，则将转化key和value的值
		for (let key = 0; key < valuesArray.length; key++) {
			// 获取当前key的value
			const value = valuesArray?.[key]?.value;
			// 获取当前key的范围
			const rangeName = getSearchForm?.[key]?.rangeName;
			// 获取当前key的格式
			const format = getSearchForm?.[key]?.format;
			// 获取当前key的名称
			const name = getSearchForm?.[key]?.name ?? "";

			if (rangeName) {
				const keyValue = Array.isArray(value) ? value : [];
				values[rangeName[0]] = Array.isArray(keyValue) ? dayjs(keyValue?.[0]).format(format as string) : "";
				values[rangeName[1]] = Array.isArray(keyValue) ? dayjs(keyValue?.[1]).format(format as string) : "";

				delete values[name];
			}
		}
		console.log("submit2", values);
		searchFinish?.(values);
	};

	// 获取搜索表单, 根据expand状态判断是否展开
	const getSearchForm = useMemo(() => {
		return searchForm?.filter((_item, index) => {
			return !expand ? index + 1 <= 24 / searchForm.length : true; // 默认列宽
		});
	}, [searchForm, expand]);

	// 获取按钮列宽
	const getBtnSpan = useMemo(() => {
		const searchLen = getSearchForm?.length;
		if (!searchLen) return 8;
		const num = 24 / defaultSpan;

		if ((searchLen - 1) % num === 0) {
			return 18;
		}
		if ((searchLen - 2) % num === 0) {
			return 12;
		}
		if ((searchLen - 3) % num === 0) {
			return 6;
		}
		if ((searchLen - 4) % num === 0) {
			return 24;
		}
	}, [getSearchForm]);

	// 设置初始值，并绑定到form，重置不清除掉值
	const initialValues = useMemo(() => {
		return getSearchForm?.reduce(
			(acc, item) => {
				acc[item.name] = item.initialValue;
				return acc;
			},
			{} as Record<string, any>,
		);
	}, [getSearchForm]);

	// 重置表单
	const resetForm = () => {
		form.resetFields();
		searchFinish?.({});
	};

	// 设置初始值，并绑定到form，用于收起展开回填值
	useEffect(() => {
		for (const item of getSearchForm ?? []) {
			form.setFieldsValue({
				[item.name]: item.initialValue,
			});
		}
	}, [getSearchForm, form]);

	return (
		<div className="mb-4 bg-white rounded-lg shadow-sm">
			<Form {...formItemLayout} form={form} initialValues={initialValues} onFinish={onFinish} layout="horizontal">
				<Row gutter={16} className="w-full">
					{getSearchForm?.length &&
						getSearchForm.map((item) => {
							const render = item?.render;
							return (
								<Col span={item?.span ?? defaultSpan} key={item.name}>
									<Form.Item name={item.name} label={item?.label}>
										{item.type === "input" && (render ? render() : <SearchInput {...item} />)}
										{item.type === "select" && <SearchSelect {...item} />}
										{item.type === "dateRange" && <SearchDatePicker {...item} />}
									</Form.Item>
								</Col>
							);
						})}
					{/* 搜索按钮 */}
					<Col span={getBtnSpan}>
						<Form.Item>
							<div className="flex gap-2 items-center justify-end">
								{searchForm?.length && searchForm?.length > 4 && (
									<div
										className="cursor-pointer"
										style={{ color: primaryColor }}
										onClick={() => {
											setExpand(!expand);
										}}
									>
										<DownOutlined rotate={expand ? 180 : 0} /> {expand ? "收起" : "展开"}
									</div>
								)}
								<Button onClick={resetForm}>重置</Button>
								<Button type="primary" htmlType="submit">
									搜索
								</Button>
							</div>
						</Form.Item>
					</Col>
				</Row>
			</Form>
		</div>
	);
};

export default TableSearch;
